package com.virgo.demo.support.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.virgo.common.exception.IApplicationException;
import com.virgo.common.utils.ICommonUtils;
import com.virgo.demo.support.converter.ConfigConverter;
import com.virgo.demo.support.domain.ConfigDo;
import com.virgo.demo.support.domain.bo.ConfigBo;
import com.virgo.demo.support.domain.vo.ConfigVo;
import com.virgo.demo.support.mapper.ConfigMapper;
import com.virgo.demo.support.service.ConfigService;
import com.virgo.redis.annotation.ICache;
import com.virgo.redis.service.CacheService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, ConfigDo> implements ConfigService {

	private final ConfigMapper configMapper;

	private final ConfigConverter configConverter;

    private final CacheService cacheService;

	/**
	 * 根据配置项key查找
	 * @param configKey String
	 * @return ConfigDo
	 */
	@Override
	public ConfigDo loadByConfigKey(String configKey) {
		LambdaQueryWrapper<ConfigDo> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ConfigDo::getConfigKey,configKey);
		queryWrapper.last(" limit 1 ");
		return getOne(queryWrapper);
	}

	/**
	 * 编辑配置项目
	 * @param configBo ConfigBo
	 */
	@Override
	public void saveConfig(ConfigBo configBo) {
		ConfigDo exist = loadByConfigKey(configBo.getConfigKey());
		ConfigDo configDo = new ConfigDo();
		BeanUtils.copyProperties(configBo,configDo);
		if (!ObjectUtils.isEmpty(exist) && !exist.getId().equals(configDo.getId())) {
			throw new IApplicationException("配置项-" + configDo.getConfigKey() + "已存在");
		}
		if (ObjectUtils.isEmpty(configDo.getId()) || configDo.getId().compareTo(0L) < 1) {
			save(configDo);
			return;
		}
        String cacheKey = "config_info_" + configBo.getConfigKey();
        cacheService.delete(cacheKey);
		updateById(configDo);
	}

	/**
	 * 系统的配置项列表
	 * @param configGroup Integer
	 * @return List<ConfigVo>
	 */
	@Override
	public List<ConfigVo> findList(Integer configGroup) {
		LambdaQueryWrapper<ConfigDo> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ConfigDo::getConfigGroup, configGroup);
		return configConverter.convert(configMapper.selectList(queryWrapper),ConfigVo.class);
	}

	/**
	 * 获取某一项的配置值
	 * @param configKey String
	 * @return String
	 */
	@Override
    @ICache(keyPrefix = "config_info", matchValue = "#configKey", ttlMin = 300, ttlMax = 600)
	public String getConfig(String configKey) {
        ConfigDo configDo = loadByConfigKey(configKey);
        if (ObjectUtils.isEmpty(configDo)) {
            return "";
        }
        return configDo.getConfigValue();
	}
}